package com.powernode.handle;

import cn.hutool.core.lang.UUID;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.HttpConstants;
import com.powernode.model.LoginResult;
import com.powernode.model.Result;
import com.powernode.util.RedisCache;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName AuthenticationSuccessHandlerImpl
 * @Description 认证成功的处理器
 * @Date 2024/07/20 20:06
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Resource
    private RedisCache redisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应头信息
        response.setContentType(HttpConstants.APPLICATION_JSON);
        request.setCharacterEncoding(HttpConstants.UTF_8);
        // 使用uuid当作token （此时token为key值，value在UserDetailServiceImpl中设置）
        String token = UUID.randomUUID().toString();
        // 从Security框架中获取认证用户对象
        redisCache.setCacheObject(AuthConstants.LOGIN_TOKEN_PREFIX + token, authentication.getPrincipal(),
                AuthConstants.TOKEN_TIME.intValue(), TimeUnit.SECONDS);
        // 封装登录统一结果对象
        LoginResult loginResult = new LoginResult(token, AuthConstants.TOKEN_TIME);
        // 响应token
        Result<LoginResult> result = Result.success(loginResult);
        String jsonObjectResult = new ObjectMapper().writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(jsonObjectResult);
        writer.flush();
        writer.close();
    }
}
